import { createRouter, createWebHashHistory } from 'vue-router'
import { addRoute, isRoute } from './layout/layout.util'

const routes = [
  {
    path: "/login",
    component: () => import('./views/login.vue'),

  },
  {
    path: "/",
    name: "layout",
    component: () => import('./layout/layout.vue'),
    children: [
      {
        path: "/403",
        component: () => import('./403.vue')
      }
    ]
  }
]

const router = createRouter({
  // 路由模式
  history: createWebHashHistory(),
  routes
})

const global = JSON.parse(localStorage.getItem("global") || "{}");

/**
 * 每次刷新后动态添加路由
 */
addRoute(router, global.roles)


/**
 * 使用全局路由守卫
 * 实现登录拦截
 */
router.beforeEach((to, form, next) => {

  /**
   * 不需要校验登录的名单
   * 白名单
   */
  const ignorePaths = ['/login', '/403', '/']

  /**
   * 白名单页面不需要校验
   */
  if (ignorePaths.includes(to.path)) {
    next()
    return
  }

  /**
 * 判断本地有没有token
 */
  if (!localStorage.getItem('token')) {
    // 如果没有跳转到登录页面
    next('/login')
    return
  }

  const global2 = JSON.parse(localStorage.getItem("global") || "{}");

  /**
   * 如果当前页面不在有权限的路由中
   * 那么需要跳转到403页面
   */
  if (!isRoute(to.path, global2.roles)) {
    next('/403')
    return
  }

  next()
})

export default router